package br.nextfm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.nextfm.dao.AlbumDao;
import br.nextfm.dao.CategoriaDao;
import br.nextfm.dao.MusicaDao;
import br.nextfm.model.Album;
import br.nextfm.model.Categoria;
import br.nextfm.model.Musica;

public class CadastraMusicaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String nome = request.getParameter("nome");
		String tags = request.getParameter("tags");
		String diretorio = request.getParameter("diretorio");
		
		int idCategoria = Integer.parseInt(request.getParameter("categoria"));
		int idAlbum = Integer.parseInt(request.getParameter("album"));

		AlbumDao albumDao = new AlbumDao();
		CategoriaDao categoriaDao = new CategoriaDao();
		MusicaDao musicaDao = new MusicaDao();

		Album album = albumDao.get(idAlbum);
		Categoria categoria = categoriaDao.get(idCategoria);
		Musica musica = new Musica(nome, diretorio, tags);

		musica.setAlbum(album);
		musica.setCategoria(categoria);
		categoria.getMusicas().add(musica);
		album.getMusicas().add(musica);
		

		if (musicaDao.insert(musica)) {

			albumDao.update(album);
			categoriaDao.update(categoria);			

		}

		else {

			request.setAttribute("erroCadastraMusica", true);

		}

		request.setAttribute("musicas", musicaDao.getAll());
		request.setAttribute("albums", albumDao.getAll());
		request.setAttribute("categorias", categoriaDao.getAll());
		request.getRequestDispatcher("musica.jsp").forward(request, response);
		
	}

}
